package com.idc.resource.service;

import com.idc.resource.dal.dto.TUserInfo;
import com.idc.resource.enums.ErrorCodeEnum;
import com.idc.resource.exception.IdcServiceException;
import com.idc.resource.manager.UserManager;
import com.idc.resource.model.LoginReqDto;
import com.idc.resource.model.UserInfoResDto;
import com.idc.resource.util.BeanMapperUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 登录服务
 * Created by Lijing on 2017/7/5.
 */
@Slf4j
@Service
public class LoginService {
    @Autowired
    private UserManager userManager;
    @Autowired
    private TokenService tokenService;

    /**
     * 登录
     * @param loginReqDto 登录请求信息
     * @return 登录用户信息
     */
    public UserInfoResDto login(LoginReqDto loginReqDto){
        TUserInfo tUserInfo = userManager.selectOne(loginReqDto.getUserId(),loginReqDto.getLoginPwd());
        if(tUserInfo==null){
            log.error("未查询到用户信息，登录失败");
            throw new IdcServiceException(ErrorCodeEnum.USER_LOSE.getCode(),ErrorCodeEnum.USER_LOSE.getDesc());
        }
        UserInfoResDto userInfo = BeanMapperUtil.objConvert(tUserInfo,UserInfoResDto.class);
        tokenService.loginIn(userInfo);
        return  userInfo;
    }

    /**
     * 用户登出
     * @param token 登录令牌
     * @return 登出结果
     */
    public Boolean loginOut(String token){
        tokenService.destroyToken(token);
        return true;
    }

}
